package com.smsclient.redission;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "redis")
@ConditionalOnProperty(value = "redis.mode", havingValue = "single")
public class RedissonSingleNodeConfig {

    private String host;
    private String port;
    private int database;
    private String password;
    private String clientName;
    private int connectionPoolSize;
    private int connectionMinimumIdleSize;
    private int idleConnectionTimeout;
    private int retryAttempts;
    private int retryInterval;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient prodRedisson() {
        Config config = new Config();
        config.setCodec(new JsonJacksonCodec());
        SingleServerConfig singleServerConfig = config.useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setDatabase(database)
                .setClientName(clientName)
                .setConnectionPoolSize(connectionPoolSize)
                .setConnectionMinimumIdleSize(connectionMinimumIdleSize)
                .setIdleConnectionTimeout(idleConnectionTimeout)
                .setRetryAttempts(retryAttempts)
                .setRetryInterval(retryInterval);
        if (StringUtils.isNotBlank(password)) {
            singleServerConfig.setPassword(password);
        }
        return Redisson.create(config);
    }

}